package com.ty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.entity.UserAddress;
import com.ty.mapper.UserAddressMapper;
import com.ty.resp.CommonResp;
import com.ty.service.IUserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 用户地址表 服务实现类
 * </p>
 *
 * @author txy
 * @since 2024-02-04
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {

    @Override
    public CommonResp getAddressByUserId(Page<UserAddress> page, String userId, String keyWord) {
        CommonResp resp = new CommonResp();
        if (!StringUtils.hasText(userId)) {
            resp.setSuccess(false);
            resp.setMessage("用户id不能为空");
        } else {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            if (StringUtils.hasText(keyWord)) {
                wrapper.like("name", keyWord)
                        .or().like("address", keyWord)
                        .or().like("phone", keyWord);
            }
            if (page != null) {
                Page<UserAddress> userAddressPage = baseMapper.selectPage(page, wrapper);
                resp.setTotal(userAddressPage.getTotal());
                resp.setContent(userAddressPage.getRecords());
            } else {
                List<UserAddress> addresses = baseMapper.selectList(wrapper);
                resp.setContent(addresses);
                resp.setTotal((long) addresses.size());
            }
        }
        return resp;
    }

    @Override
    public CommonResp getAddressById(String addrId, String userId) {
        //根据id获取地址
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.eq("id", addrId);
        CommonResp resp = new CommonResp();
        UserAddress userAddress = baseMapper.selectOne(wrapper);
        resp.setSuccess(userAddress != null);
        resp.setContent(userAddress);
        return resp;
    }

    @Override
    public CommonResp deleteAddressById(String addrId) {
        CommonResp resp = new CommonResp();
        if (StringUtils.hasText(addrId)) {
            int i = baseMapper.deleteById(addrId);
            if (i > 0) {
                resp.setMessage("删除成功");
            } else {
                resp.setMessage("删除失败");
                resp.setSuccess(false);
            }
        } else {
            resp.setMessage("删除的id不能是空");
            resp.setSuccess(false);
        }
        return resp;
    }
}
